package com.wjn.basic.thread.AqsDemo;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * countDownLatch这个类使一个线程等待其他线程各自执行完毕后再执行。
 * 计数器，当计数器为0的时候，执行main函数，不具备重复性
 */
public class CountDownLatchDemo {



    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(2);
        System.out.println("主线程开始执行…… ……");
        //第一个子线程执行
        ExecutorService es1 =Executors.newCachedThreadPool();
        es1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    System.out.println("第一个线程："+Thread.currentThread().getName()+"执行");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();
                System.out.println("thread counts = " + (latch.getCount()));
            }
        });

        //java8的形式
        es1.execute(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第二个线程："+Thread.currentThread().getName()+"执行");
            latch.countDown();
            System.out.println("thread counts = " + (latch.getCount()));
        });
        es1.shutdown();

        System.out.println("等待两个线程执行完毕…… ……");
        try {
            latch.await();
            System.out.println("concurrency counts = " + (2 - latch.getCount()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("两个子线程都执行完毕，继续执行主线程");
    }


}
